package app.beit.finportal.dao;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;

import app.beit.finportal.entity.BaseEntity;

public abstract class BaseDao<T extends BaseEntity> {

	@Autowired
	protected SessionFactory sessionFactory;
	
//	private Long getNextKey(final String sequenceName) throws Exception{
//		final StringBuilder sql = new StringBuilder();
//		sql.append("select ").append(sequenceName).append(".nextval from dual");
//		final Session session = this.sessionFactory.openSession();		
//	    final Query query = session.createSQLQuery(sql.toString());
//	    final String s = query.uniqueResult().toString();
//	    final Long key = Long.parseLong(s);
//		session.close();
//	    return key;
//	}
	
	public void add(final T entity) throws Exception{
//		entity.setId(this.getNextKey(sequenceName));
		final Session session = this.sessionFactory.openSession();
		final Transaction tr = session.beginTransaction();
		session.save(entity);
		tr.commit();
		session.close();
	}
	
	public void update(final T entity) throws Exception{
		final Session session = this.sessionFactory.openSession();
		final Transaction tr = session.beginTransaction();
		session.update(entity);
		tr.commit();
		session.close();
	}
	
	public void delete(final T entity) throws Exception{
		final Session session = this.sessionFactory.openSession();
		final Transaction tr = session.beginTransaction();
		session.delete(entity);
		tr.commit();
		session.close();
	}
	
}
